from flask import Blueprint, render_template, jsonify, request
from models.entity.district import District
from models.entity.device import Device
from models.entity.district_item import DistrictItem
import json
from utils.nodetree import get_district_tree
from models.entity.district_with_facility import DistrictWithFacility
from models.entity.district_with_device import DistrictWithDevice
from utils.result import result

mod = Blueprint("core_district", __name__, url_prefix="/core/district", template_folder="templates",
                static_folder="static")


#这个项目用于主分区管理
#
# @mod.route('/add/', methods=['GET', 'POST'])
# def add_district():
#     #新增主分区
#     #ParentId的值不能为空
#     """
#     {
#     "code":"k564k",
#     "dis_order":"10",
#     "name":"b45654165j",
#     "description":"ddd",
#     "status":1
#     "parent_id":1
#     "lat":38.0025,
#     "lng":38.223,
#     "item":[item1, item2]
#     }
#     """
#     if request.method == 'POST':
#         dict = json.loads(request.data.decode("utf-8"))
#         print('dict', dict)
#         if "id" in dict:
#             dict.pop("id")
#         if 'item' in dict:
#             items = dict.pop("item")
#             print('items', items)
#             # dict.pop("item")
#         if District.get_district_by_name(dict["name"]):
#             return result(success=0, error_code=-1, error_msg='名称已经存在')
#         if District.get_district_by_code(dict["code"]):
#             return result(success=0, error_code=-1, error_msg='编码已经存在')
#         district = District()
#         try:
#             district.from_dict(dict)
#         except RuntimeError as e:
#             return result(success=0, error_msg=str(e), error_code=-1)
#         try:
#             if district.save():
#                 print('分区保存了')
#                 # for old_point in district.get_points_by_district_id(district.id):
#                 #     print('old_point', old_point)
#                 #     if old_point.delete() is False:
#                 #         return result(success=0, error_code=-3, error_msg="分区点删除错误")
#                     # if old_point.delete():
#                     #     return result(success=1, error_code=-3, error_msg="分区点删除")
#                 for tt in items:
#                     # np = DistrictItem()
#                     if 'id' in tt:
#                         print('tt', tt)
#                         np = DistrictItem.get_district_item_by_id(tt['id'])
#                         np.lng = tt["lng"]
#                         np.lat = tt["lat"]
#                         np.dis_order = tt["dis_order"]
#                         np.district_id = district.id
#                     else:
#                         print('else')
#                         print('tt', tt)
#                         np = DistrictItem()
#                         print('np')
#                         np.lng = tt["lng"]
#                         np.lat = tt["lat"]
#                         np.dis_order = tt["dis_order"]
#                         print('dis')
#                         np.district_id = district.id
#
#                     if np.save() is False:
#                         return result(success=0, error_code=-3, error_msg='分区点保存错误')
#
#                 return result(success=1)
#             else:
#                 return result(success=0, error_code=-3, error_msg='未知错误')
#
#         except RuntimeError as e:
#             return result(success=0, error_msg=str(e), error_code=-1)




# 我的添加分区方法
# @mod.route('/add/', methods=['GET', 'POST'])
# def add_district():
#     """新增主分区"""
#     """ParentId的值不能为空"""
#     """
#     {
#     "code":"k564k",
#     "dis_order":10,
#     "name":"b45654165j",
#     "description":"ddd",
#     "status":1
#     "parent_id":1
#     "lat":38.0025,
#     "lng":38.223,
#     "item":[item1, item2]
#     }
#     """
#     if request.method == 'POST':
#         tmp = {}
#         dict = json.loads(request.data.decode("utf-8"))
#         data = []
#         if "name" not in dict:
#             tmp['success'] = 0
#             tmp['error_code'] = -1
#             tmp['error_msg'] = "名称不能为空"
#             tmp['data'] = data
#             return jsonify(tmp)
#         name = str(dict['name']).strip()
#         if "code" not in dict:
#             tmp['success'] = 0
#             tmp['error_code'] = -1
#             tmp['error_msg'] = "编码不能为空"
#             tmp['data'] = data
#             return jsonify(tmp)
#         code = str(dict['code']).strip()
#         description = dict['description']
#         dis_order = dict['dis_order']
#         status = int(dict['status'])
#         parent_id = int(dict['parent_id'])
#         if dict['lng'] is None:
#             lng=0
#         else:
#             lng = float(dict['lng'])  # 经度
#         if dict['lat'] is None:
#             lat=0
#         else:
#             lat = float(dict['lat'])  # 经度
#         items = dict["item"]
#         print('item', items)
#         if District.get_district_by_name(name):
#             tmp['success'] = 0
#             tmp['error_code'] = -2
#             tmp['error_msg'] = "名称已存在，请重新设置"
#             tmp['data'] = data
#             return jsonify(tmp)
#         if District.get_district_by_code(code):
#             tmp['success'] = 0
#             tmp['error_code'] = -2
#             tmp['error_msg'] = "编码已存在，请重新设置"
#             tmp['data'] = data
#             return jsonify(tmp)
#         district = District()
#         district.name = name
#         district.code = code
#         district.lng = lng
#         district.lat = lat
#         district.description = description.strip()
#         district.dis_order = int(dis_order)
#         district.status = int(status)
#         district.parent_id = parent_id
#         if district.save():
#             for tt in items:
#                 print('tt', tt)
#                 np=DistrictItem()
#                 np.lng=tt["lng"]
#                 np.lat=tt["lat"]
#                 np.dis_order=tt["dis_order"]
#                 np.district_id=district.id
#                 print('ff')
#                 if np.save() is False:
#                     print('np保存错了')
#                     tmp['success']=0
#                     tmp['error_code']=-3
#                     tmp['error_msg']='分区点保存错误'
#                     return jsonify(tmp)
#             tmp['success'] = 1
#             tmp['error_code'] = None
#             tmp['error_msg'] = None
#             tmp['data'] = data
#             print('district保存了')
#             return jsonify(tmp)
#         else:
#             tmp['success'] = 0
#             tmp['error_code'] = -3
#             tmp['error_msg'] = "unexcept Error"
#             tmp['data'] = data
#             return jsonify(tmp)


@mod.route('/add/', methods=['GET', 'POST'])
def add_district():
    """新增主分区"""
    """ParentId的值不能为空"""
    """
    {
    "code":"k564k",
    "dis_order":"10",
    "name":"b45654165j",
    "description":"ddd",
    "status":1
    "ParentId":1
    "lat":38.0025,
    "lng":38.223,
    "item":[item1, item2]
    }
    """
    if request.method == 'POST':
        tmp = {}
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        data = []
        if "name" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "名称不能为空"
            tmp['data'] = data
            return jsonify(tmp)
        name = dict['name'].strip()
        if "code" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "编码不能为空"
            tmp['data'] = data
            return jsonify(tmp)
        code = dict['code']
        description = dict['description']
        dis_order = dict['dis_order']
        status = int(dict['status'])
        parent_id = int(dict['parent_id'])
        if dict['lng'] is None:
            lng=0
        else:
            lng = float(dict['lng'])  # 经度
        if dict['lat'] is None:
            lat=0
        else:
            lat = float(dict['lat'])  # 经度
        item=dict["item"]
        if District.get_district_by_name(name):
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "名称已存在，请重新设置"
            tmp['data'] = data
            return jsonify(tmp)
        if District.get_district_by_code(code):
            tmp['success'] = 0
            tmp['error_code'] = -2
            tmp['error_msg'] = "编码已存在，请重新设置"
            tmp['data'] = data
            return jsonify(tmp)
        district = District()
        print('district.id-save前', district.id)
        district.name = name
        district.code = code
        district.lng = lng
        district.lat = lat
        district.description = description.strip()
        district.dis_order = int(dis_order)
        district.status = int(status)
        district.parent_id = parent_id
        if district.save():
            print('district.id-save后', district.id)
            for tt in item:
                np=DistrictItem()
                np.lng=tt["lng"]
                np.lat=tt["lat"]
                np.dis_order=tt["dis_order"]
                np.district_id=district.id
                if np.save() is False:
                    tmp['success']=0
                    tmp['error_code']=-3
                    tmp['error_msg']='分区点保存错误'
                    return jsonify(tmp)
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "unexcept Error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/del/', methods=['GET', 'POST'])
def del_district():
    """删除主分区"""  # 正常
    """
    {
    "id": 1
    }
    """
    if request.method == 'POST':
        dict = json.loads(request.data.decode("utf-8"))
        id = dict['id']
        data = []
        tmp = {}
        district = District.get_district_by_id(id)
        # 删除所有分区点
        district_item_all = DistrictItem.get_district_items_by_district(district.id)
        for item in district_item_all:
            if item.delete() is False:
                return result(success=0, error_code=-4, error_msg='分区点删除错误')
        if not district:
            return result(success=0, error_code=-1, error_msg="该分区不存在，请重新选择")
        if District().get_list_by_pid(id):
            return result(success=0, error_code=-1, error_msg="该点存在子节点，请先删除子节点")
        # dict中如果还有关联对应的dict_category
        # 删除分区与设施的中间表关联
        for item in DistrictWithFacility.query.filter_by(district_id=id).all():
            if item.delete() is False:
                return result(success=0, error_code=-3, error_msg="未知错误")
        # 删除分区与设备的中间表关联
        for item in DistrictWithDevice.query.filter_by(district_id=id).all():
            if item.delete() is False:
                return result(success=0, error_code=-4, error_msg="未知错误")
        if district.delete():
            return result(success=1)
        else:
            return result(success=0, error_msg='未知错误', error_code=-6)


@mod.route('/get_all/', methods=['GET', 'POST'])
def get_all_district():
    """得到字典项目分类"""   # 可用
    district_masters = District.get_district_all()
    data = []
    tmp = {}
    for item in district_masters:
        district_item_list = DistrictItem.get_district_items_by_district(item.id)
        tlist = []
        for p in district_item_list:
            tlist.append(p.get_dic())
        data.append({"id": +item.id, "name": item.name, "code": item.code,
                     "description": item.description, "lat": item.lat, "lng": item.lng,
                     "dis_order": item.dis_order, "status": item.status,
                     "parent_id": item.parent_id, "level": item.depth, "district_item": tlist})
    return result(data=data)


@mod.route('/get_tree_all/', methods=['GET', 'POST'])
def get_tree_all():
    """得到字典项目分类"""      # 可用
    all_tree_node = []
    district_roots = District().get_list_by_pid(0)  # 得到所有的根节点
    print('根节点个数', len(district_roots)) # 12
    for item in district_roots:
        t_list = []  #
        for t in District.query.all():
            if t.path.split(',')[0] == str(item.id):
                t_list.append(t)
        print('t_list长度', len(t_list), t_list)
        all_tree_node.append(t_list)
    print('all_tree_node', all_tree_node)
    # all_tree_node [[<District_item 测试分区1>, <District_item 111>, <District_item cui1>, <District_item 124>,
    # <District_item 2121>, <District_item 123123qwe>],        [<District_item 222>], [<District_item 333>],
    #  [<District_item 1212>], [<District_item 12>], [<District_item 123123>], [<District_item 12123123>],
    # [<District_item qwe>], [<District_item 1231qwe>], [<District_item qeqe>], [<District_item 12312>],
    #  [<District_item qweqweqw>]]

    rlist = []
    count = 0
    while count < len(district_roots):  # 12个顶层
        rlist.append(get_district_tree(all_tree_node[count], 0)[0])
        count += 1
    return result(data=rlist)


"""
@mod.route('/edit', methods=['GET', 'POST'])
def edit_district_master():
    得到字典列表中的字典项"""


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_district():
    """增加字典项目分类"""
    """
    {
    "id":2,
    "code":"k564k",
    "dis_order":"10",
    "name":"b45654165j",
    "description":"ddd",
    "status":1
    "ParentId":0,
    "lat":111.99,
    "lng":112.99,
    "item":[item1,item2,...]
    }
    """
    if request.method == 'POST':
        dict = json.loads(request.data.decode("utf-8"))
        id = dict['id']
        items = dict.pop("item")
        print('point_item', items)
        #point_item [{'district_id': 3, 'dis_order': 1, 'id': 519, 'lat': 37.827, 'lng': 112.558},
        district = District.get_district_by_id(id)
        try:
            district.from_dict(dict)
        except RuntimeError as e:
            return result(success=0, error_code=-2, error_msg=str(e))
        if district.save():
            for old_point in district.get_points_by_district_id(district.id):
                print('old_point', old_point)
                if old_point.delete() is False:
                    return result(success=0, error_code=-3, error_msg="分区点删除错误")
                if old_point.delete():
                    return result(success=1, error_code=-3, error_msg="分区点删除")
            for tt in items:
                # np = DistrictItem()
                if 'id' in tt:
                    np = DistrictItem.get_district_item_by_id(tt['id'])
                    np.lng = tt["lng"]
                    np.lat = tt["lat"]
                    np.dis_order = tt["dis_order"]
                    np.district_id = district.id
                else:
                    np = DistrictItem()
                    np.lng = tt["lng"]
                    np.lat = tt["lat"]
                    np.dis_order = tt["dis_order"]
                    np.district_id = district.id

                if np.save() is False:
                    return result(success=0, error_code=-3, error_msg='分区点保存错误')

            return result(success=1)
        else:
            return result(success=0, error_code=-3, error_msg='未知错误')
        # res=district.edit(name,code,description,dis_order,status,parent_id,lat,lng,items)


@mod.route("/search/", methods=["POST"])
def search_device_type():
    """
    查询button
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    # if request.method == 'POST':
    #     receive = request.get_data()
    #     data = json.loads(receive.decode("utf-8"))
    #     tmp = {}
    #     extra = []
    #     if 'query_word' in data:
    #         query_word = data['query_word']
    #     else:
    #         tmp['success'] = 0
    #         tmp['error_code'] = -9
    #         tmp['error_msg'] = "数据格式错误"
    #         tmp['data'] = extra
    #         return jsonify(tmp)
    #     districts = District.search(query_word)
    #     return jsonify(districts)


    try:
        if request.method == "POST":
            print(111)
            data = json.loads(request.data.decode("utf-8"))
            print(data)
    except:
        return result(success=0,error_code=-1,error_msg="json格式错误")

    if "query_word" in data:
        query_word = data["query_word"]
        # print('query_word',query_word)
    else:
        return result(success=0,error_code=-2,error_msg="数据不完整")
    rdic = District.search(query_word)
    print(1111111111)
    print(rdic)
    print(2222222222)
    return jsonify(rdic)

    def get_max_id(self):
        val = db_store.session.query(func.max(Alarm.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):

        if self.id is None:
            self.id = self.get_max_id() + 1
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print("error is ")
            print(e)
            db_store.session.rollback()
            return False
